/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PhanLoai.java
 *
 * Created on Nov 2, 2012, 10:25:26 PM
 */
package pl_cmts;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Kojino
 */
public class PhanLoai extends javax.swing.JFrame {

    /** Creates new form PhanLoai */
    public PhanLoai() {
        initComponents();       
    }
    N_gram ngram = new N_gram();
    int n=0;
    int Pos, Neg, Neu, SPos, SNeg, SNeu;
    /***************/
    public void inDulieu(HashMap<String,word> hmap){
        ArrayList<word> AL = toAL(hmap);
        Collections.sort(AL, new sxtu());
        DefaultTableModel c = (DefaultTableModel) jTable_dsTuKhoa.getModel();
        c.getDataVector().removeAllElements();
        c.fireTableDataChanged();
        for(int i=0; i<AL.size(); i++){
            word tu = AL.get(i);
            c.addRow(new Object[]{i+1,tu.getTu(),tu.getSolan()});
        }
    }
    public ArrayList<word> toAL(HashMap<String,word> hmap){
        ArrayList<word> A = new ArrayList<word>();
        Set set = hmap.keySet();
        Iterator iter = set.iterator();
        while(iter.hasNext()){
            word w = hmap.get(iter.next()); 
            A.add(w);
        }
        return A;
    }
    
    public HashMap<String,word> layDsTu(){
        HashMap<String, word> dsTuKhoa = new HashMap<String, word>();
        for(int i=0; i<20; i++){
            if(jTable_dsTuKhoa.getValueAt(i, 3)==null) {JOptionPane.showMessageDialog(this, "Chưa điền trọng số cho từ số"+(i+1)); break;}
            String tu = jTable_dsTuKhoa.getValueAt(i, 1).toString();
            int solan = Integer.parseInt(jTable_dsTuKhoa.getValueAt(i, 2).toString());
            int trongso = Integer.parseInt(jTable_dsTuKhoa.getValueAt(i, 3).toString());  
            word w = new word(tu, solan, trongso);
            dsTuKhoa.put(tu, w);
        }
        return dsTuKhoa;
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable_dsTuKhoa = new javax.swing.JTable();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        Ngram = new javax.swing.JButton();
        LuuDuLieu = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        ketqua = new javax.swing.JTextArea();
        key = new javax.swing.JTextField();
        PhanLoai = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable_dsTuKhoa.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "STT", "Từ", "Số lần", "Trọng số"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable_dsTuKhoa.setColumnSelectionAllowed(true);
        jScrollPane1.setViewportView(jTable_dsTuKhoa);
        jTable_dsTuKhoa.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setText("Uni-gram");

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setText("Bi-gram");

        buttonGroup1.add(jRadioButton3);
        jRadioButton3.setText("Tri-gram");

        Ngram.setText("N-gram");
        Ngram.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NgramActionPerformed(evt);
            }
        });

        LuuDuLieu.setText("Lưu dữ liệu luyện tập");
        LuuDuLieu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LuuDuLieuActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(205, Short.MAX_VALUE)
                .addComponent(Ngram)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jRadioButton3)
                    .addComponent(jRadioButton2)
                    .addComponent(jRadioButton1))
                .addGap(78, 78, 78)
                .addComponent(LuuDuLieu)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(LuuDuLieu, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jRadioButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jRadioButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jRadioButton3))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addComponent(Ngram, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jTabbedPane1.addTab("Huấn luyện", jPanel1);

        ketqua.setColumns(20);
        ketqua.setRows(5);
        jScrollPane2.setViewportView(ketqua);

        PhanLoai.setText("Bắt đầu");
        PhanLoai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PhanLoaiActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(key, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(183, 183, 183)
                .addComponent(PhanLoai)
                .addGap(23, 23, 23))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(key, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(PhanLoai))
                .addGap(44, 44, 44)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Phân Loại", jPanel2);

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 569, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void NgramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NgramActionPerformed
// TODO add your handling code here:
    ArrayList<String> dsTu = new ArrayList<String>();
    HashMap<String, word> HMTu = new HashMap<String, word>(); 
    if(jRadioButton1.isSelected()) n=1;
    if(jRadioButton2.isSelected()) n=2;
    if(jRadioButton3.isSelected()) n=3;
    if(n==0) JOptionPane.showMessageDialog(this, "Chưa chọn loại N-gram !!!");
    try {
        FileInputStream fi = new FileInputStream("input.txt");
        InputStreamReader isr = new InputStreamReader(fi, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String cmt;
        while ((cmt = br.readLine()) != null){
            //System.out.println(cmt);
            dsTu = ngram.ngrams(n, cmt);    
            HMTu = ngram.them_tu(dsTu, HMTu);
        }
        inDulieu(HMTu);   
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }    
}//GEN-LAST:event_NgramActionPerformed

private void LuuDuLieuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LuuDuLieuActionPerformed
// TODO add your handling code here:
    Pos = Neu = Neg = SPos = SNeg = SNeu = 0;
    ArrayList<String> dsTu = new ArrayList<String>();
    HashMap<String, word> HMTu = new HashMap<String, word>(); 
    HashMap<String, word> dsTuKhoa = layDsTu();
    try {
        FileInputStream fi = new FileInputStream("input.txt");
        InputStreamReader isr = new InputStreamReader(fi, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String cmt;
        while ((cmt = br.readLine()) != null){
            int tmp =0;
            dsTu = ngram.ngrams(n, cmt);
            HMTu = ngram.them_tu(dsTu, HMTu);
            Set set = HMTu.keySet();
            Iterator iter = set.iterator();
            Iterator iter2 = set.iterator();
            while(iter.hasNext()){
                word w = HMTu.get(iter.next());
                if(dsTuKhoa.containsKey(w.getTu())){
                    tmp = tmp + w.getSolan()*dsTuKhoa.get(w.getTu()).getTrongso();   
                }
            }
            if(tmp>0){
                Pos++;
                while(iter2.hasNext()){
                    word w = HMTu.get(iter2.next());
                    if(dsTuKhoa.containsKey(w.getTu())){
                        SPos = SPos + w.getSolan();
                        word tukhoa = dsTuKhoa.get(w.getTu());
                        tukhoa.setSolanPos(tukhoa.getSolanPos()+w.getSolan());
                        dsTuKhoa.put(tukhoa.getTu(), tukhoa);
                    }
                }
            }
            if(tmp==0){
                Neu++;
                while(iter2.hasNext()){
                    word w = HMTu.get(iter2.next());
                    if(dsTuKhoa.containsKey(w.getTu())){
                        SNeu = SNeu + w.getSolan();
                        word tukhoa = dsTuKhoa.get(w.getTu());
                        tukhoa.setSolanPos(tukhoa.getSolanNeu()+w.getSolan());
                        dsTuKhoa.put(tukhoa.getTu(), tukhoa);
                    }
                }
            }
            if(tmp<0){
                Neg++;
                while(iter2.hasNext()){
                    word w = HMTu.get(iter2.next());
                    if(dsTuKhoa.containsKey(w.getTu())){
                        SNeg = SNeg + w.getSolan();
                        word tukhoa = dsTuKhoa.get(w.getTu());
                        tukhoa.setSolanPos(tukhoa.getSolanNeg()+w.getSolan());
                        dsTuKhoa.put(tukhoa.getTu(), tukhoa);
                    }
                }
            }
        }  
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }    
    System.out.println(Pos+" "+Neg+" "+Neu+" "+SPos+" "+SNeg+" "+SNeu);
}//GEN-LAST:event_LuuDuLieuActionPerformed

private void PhanLoaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PhanLoaiActionPerformed
// TODO add your handling code here:
    ArrayList<String> dsTu = new ArrayList<String>();
    HashMap<String, word> HMTu = new HashMap<String, word>(); 
    HashMap<String, word> dsTuKhoa = layDsTu();
    int ok = 0;
    //whie(cac cmt can phan loai chua het){
    double P_Pos = (double)Pos/(Pos+Neg+Neu);
    double P_Neg = (double)Neg/(Pos+Neg+Neu);
    double P_Neu = (double)Neu/(Pos+Neg+Neu);
    String cmt = key.getText(); 
    dsTu = ngram.ngrams(n, cmt);
    HMTu = ngram.them_tu(dsTu, HMTu);
    Set set = HMTu.keySet();
    Iterator iter = set.iterator();
    while(iter.hasNext()){
        word w = HMTu.get(iter.next());
        if(dsTuKhoa.containsKey(w.getTu())){
            double P_w_Pos = (double)(dsTuKhoa.get(w.getTu()).getSolanPos()+1)/(SPos+20);System.out.println("P_w_Pos ="+P_w_Pos);
            P_Pos = (double)(P_Pos*w.getSolan()*P_w_Pos);
            double P_w_Neg = (double)(dsTuKhoa.get(w.getTu()).getSolanNeg()+1)/(SNeg+20);System.out.println("P_w_Neg ="+P_w_Neg);
            P_Neg = (double)(P_Neg*w.getSolan()*P_w_Neg);
            double P_w_Neu = (double)(dsTuKhoa.get(w.getTu()).getSolanNeu()+1)/(SNeu+20);System.out.println("P_w_Neu ="+P_w_Neu);
            P_Neu = (double)(P_Neu*w.getSolan()*P_w_Neu);
            ok=1;
        }
    }
    double max =0; System.out.println(P_Pos+" "+P_Neg+" "+P_Neu);
    int k = 0;
    if(P_Pos>max) {max = P_Pos; k=1;}
    if(P_Neg>max) {max = P_Neg; k=2;}
    if(P_Neu>max) {max = P_Neu; k=3;} System.out.println("MAX = "+max+"  k="+k);
    if(ok==0) k=3;
    switch(k){
            case 1:
                ketqua.setText("Positive "+cmt); break;
            case 2:
                ketqua.setText("Negative "+cmt); break;
            case 3:
                ketqua.setText("Neutral "+cmt); break;
    }
}//GEN-LAST:event_PhanLoaiActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PhanLoai.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PhanLoai.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PhanLoai.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PhanLoai.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PhanLoai().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton LuuDuLieu;
    private javax.swing.JButton Ngram;
    private javax.swing.JButton PhanLoai;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable_dsTuKhoa;
    private javax.swing.JTextArea ketqua;
    private javax.swing.JTextField key;
    // End of variables declaration//GEN-END:variables
}
